package netudp;

import javax.xml.crypto.Data;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Date;

public class J_UdpServer {
    public static void main(String[] args){
        DatagramSocket dSocket;
        DatagramPacket inPacket;
        DatagramPacket outPacket;
        InetAddress cAddress;
        int cPort;
        byte[] inBuffer = new byte[100];
        byte[] outBuffer;
        String s;

        try {
            dSocket = new DatagramSocket(8000);
            while (true){
                inPacket = new DatagramPacket(inBuffer,inBuffer.length);
                dSocket.receive(inPacket); //接收数据报
                cAddress = inPacket.getAddress();
                cPort = inPacket.getPort();
                s = new String(inPacket.getData(),0,inPacket.getLength());
                System.out.println("接收到客户端信息："+s);
                System.out.println("客户端主机名称为："+cAddress.getHostName());
                System.out.println("客户端端口号为："+cPort);

                Date d = new Date();
                outBuffer = d.toString().getBytes();
                outPacket = new DatagramPacket(outBuffer,outBuffer.length,cAddress,cPort);
                dSocket.send(outPacket);
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
